import {
  setSessionItem,
  getSessionItem,
  removeSessionItem,
  ishasAgentId
} from "@/basa/utils";

import {
  listSettlementWritePage,
  removeSettlementWrite,
  revokeSettlementWrite
} from "../api/settlement-written-off.js";
import approvalState from "@/config/mixins/smp-state";

export default {
  mixins: [approvalState],
  data() {
    return {
      isActive: 0,
      multiDataToEnd: {},
      singleDataToEnd: {},
      // 表格相关
      tableData: [], // 表格数据
      draggFlag: true,
      focuses: [
        { focus: "all" },
        { focus: "unsubmitted" },
        { focus: "approval" },
        { focus: "return" }
      ],
      tableName: this.tableList.settlementWrittenOffAll, // 表格命名
      tableThead: [], // 表格数据

      // 非锁定表格
      unfixedTableThead: [
        {
          label: "冲销单名称",
          prop: "writeoffName",
          width: "300"
        },
        {
          label: "结算单编号",
          prop: "settlementCode",
          width: "150"
        },
        {
          label: "填报单位",
          prop: "reportInOrgName",
          width: "200"
        },
        {
          label: "合同编号",
          prop: "contractCode",
          width: "150"
        },
        {
          label: "合同正式编号",
          prop: "formalContractCode",
          width: "150"
        },
        {
          label: "合同名称",
          prop: "contractName",
          width: "300"
        },
        {
          label: "供应商",
          prop: "supplierName",
          width: "200"
        },      
        {
          label: "单据状态",
          prop: "billStatus",
          width: "70"
        }
      ],
      unfixedTableTheadTow: [],

      // 动态表格
      tableTheadOptions: [],
      // 弹框表格
      // popoverShow: false,
      selectRow: [],
      selectData: [],
      isFocus: 1,
      // 表格相关 end
      // 高级搜索数据 start
      formData: {
        changeCode: "",
        changeName: "",
        declareDate: "",
        declareAmount: "",
        supplierName: "",
        replyDate: "",
        replyAmount: "",
        contractStatus: "",
        reportInOrgName: ""
      }, // 高级搜索提交数据
      formDataSearch: "",
      localSearchData: {},
      isShowSearch: true,
      // 高级搜索数据 end
      isShowPagination: false, //无数据的不展示底部全选，批量删除
      // 全选以及页码
      totalNum: 0,
      total: 0,
      isIndeterminate: false,
      checkAll: false,
      value: "",
      pageNoCode: this.getLocalPageNo(),
      pageSizeCode: 10,
      // isFist: false,
      // 全选以及页码 end
      // 表格数据删除相关
      delDemoId: "",
      content: "您确定要删除吗？",
      typeDel: "", //有关批量删除
      isSelection: false,
      // 表格数据删除相关 end
      // 排序入参所需字段
      sortord: "",
      sortprop: "",

      // 表格数据相关处理 end
      form: {}
    };
  },

  methods: {
    //去空格
    handleTrim(key) {
      this.$set(
        this.formData,
        key,
        this.formData[key].replace(/(^\s*)|(\s*)$/g, "")
      );
    },
    change(index, key, value) {
      const formDataKeys = Object.keys(this.formData);
      formDataKeys.map(_ => {
        if (_ !== key) this.formData[_] = "";
      });
    },
    //切换列表
    tabChange(data) {
      this.$router.push({ name: `settlement-write-${data}` });
    },
    //初始化
    initData() {
      this.setTableWidth();
    },
    // 列表数据请求billStatus
    getList(reqObj) {
      let obj = {};
      obj = typeof reqObj == "object" ? reqObj : obj;
      obj.pageNo = this.pageNoCode;
      obj.pageSize = this.pageSizeCode;
      obj.isShowPageLoading = true;
      if (this.isActive == 1) {
        obj.labelType = "1";
      } else if (this.isActive == 2) {
        obj.labelType = "2";
      } else if (this.isActive == 3) {
        obj.labelType = "3";
      } else {
        obj.labelType = "0";
      }
      listSettlementWritePage(obj).then(res => {
        this.tableData = res.data.data.rows;
        this.tableData.forEach(item => {
          item.statusCode = item.billStatus;
          item.billStatus = this.smpScStatusTypeName[Number(item.billStatus)];
        });
        this.totalNum = res.data.data.recordsTotal;
        this.isShowPagination = res.data.data.rows.length > 0;
      });
    },
    // 跳转编辑页
    handleGoEdit(row) {
      this.$router.push(
        `/settlement-management/settlement-written-off/settlement-edit/${row.id}`
      );
    },
    // 到详情
    handleGoDetail(row, isApproval) {
      console.log(row.billStatus);
      if(row.billStatus == "待提交"){
        this.$router.push(
          `/settlement-management/settlement-written-off/detail-item/${row.id}`
        );
      }else{
        this.$router.push(
          `/settlement-management/settlement-written-off/detail-approval/${row.id}`
        );
      }
      // if (isApproval != 1) {
      //   //是全部列表时要看审批状态决定跳哪个页,approvalStatus为空是编辑中
      //   if (row.approvalStatus !== "") {
      //     this.$router.push(
      //       `/settlement-management/settlement-written-off/detail-approval/${row.id}`
      //     );
      //   } else {
      //     this.$router.push(
      //       `/settlement-management/settlement-written-off/detail-item/${row.id}`
      //     );
      //   }
      // } else {
      //   this.$router.push(
      //     `/settlement-management/settlement-written-off/detail-approval/${row.id}`
      //   );
      // }
    },
    // 删除
    handleDelete(row) {
      this.$confirm("您确定要删除吗？", "删除确认", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "ccui-message-box-custom"
      })
        .then(() => {
          const obj = {
            id: row.id
          };
          removeSettlementWrite(obj).then(res => {
            this.getList(this.formDataSearch);
          });
        })
        .catch(() => {});
    },
    // 退回
    handleRevoke(row) {
      this.$confirm("您确定要撤回吗？", "撤回确认", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "ccui-message-box-custom"
      })
        .then(() => {
          const obj = {
            id: row.id
          };
          revokeSettlementWrite(obj).then(res => {
            this.$message({
              type: "success",
              message: "撤回成功"
            });
            this.getList(this.formDataSearch);
          });
        })
        .catch(() => {});
    },
    // 新增
    handleGoNew() {
      this.$router.push(
        "/settlement-management/settlement-written-off/settlement-new"
      );
    },

    // 表格弹框拖拽触发
    handleTableChange(val) {
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      this.tableTheadOptions = localTableData;
    },

    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 表格宽度更改存入
    tableTitleWidth(newWidth, oldWidth, column, event) {
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (this.unfixedTableThead[i].label === column.label) {
          this.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
      this.draggFlag = false;
      this.$nextTick(() => {
        this.draggFlag = true;
      });
    },
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "rgba(255,232,195,1) " };
      }
    },

    // 上一页
    handlePrev() {
      console.log("上一页");
    },
    // 下一页
    handleNext() {
      console.log("下一页");
    },
    // 每页条数发生改变
    handleSizeChange(val) {
      this.pageNoCode = 1;
      if (val !== "none") {
        this.pageSizeCode = val;
        setSessionItem("pageSize", this.tableName, val);
      }
      this.getList(this.formDataSearch);
    },
    // 当前页发生改变
    handleCurrentChange(val) {
      let searchFormData = getSessionItem("pageNo", this.tableName) || {};
      setSessionItem("pageNo", this.tableName, {
        pageNo: val,
        searchForm: searchFormData.searchForm || {}
      });
      this.formDataSearch = {
        ...this.formDataSearch,
        ...searchFormData.searchForm
      };
      // 跳转翻页都会调这个方法
      this.pageNoCode = val;
      this.getList(this.formDataSearch);
    },
    // 高级搜索所需函数 start
    // 高级搜索展开按钮
    search(searchData) {
      this.pageNoCode = 1;
      this.formDataSearch = searchData;
      this.localSearchData = JSON.parse(JSON.stringify(searchData));
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
      console.log("121212121", this.formDataSearch);
      this.getList(this.formDataSearch);
    },
    // 高级搜索 end

    // 默认显示多少条
    getLocalPageSize() {
      return getSessionItem("pageSize", this.tableName) || 10;
    },
    // 读取当前页缓存
    getLocalPageNo() {
      let localData = getSessionItem(
        "pageNo",
        this.tableList.settlementWrittenOffAll
      );
      return (localData && localData.pageNo) || 1;
    }
  },

  mounted() {
    this.initData();
  },
  beforeRouteLeave(to, from, next) {
    removeSessionItem("pageNo");
    for (var key in this.$vnode.parent.parent.componentInstance.cache) {
      delete this.$vnode.parent.parent.componentInstance.cache[
        ishasAgentId(to.path, key)
      ];
    }
    next();
  },

  activated() {
    if (Object.keys(this.localSearchData).length > 0) {
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
    }
    let localData = getSessionItem(
      "pageNo",
      this.tableList.settlementWrittenOffAll
    );
    let data = localData && localData.searchForm;
    this.getList({ ...this.formDataSearch, ...data });
  }
};
